import { Component } from 'react';
import axios from 'axios';
import { notification } from 'antd';
import 'es6-promise';
import $ from 'jquery';
// eslint-disable-next-line import/named
import defaultSettings from '../../config/defaultSettings';

const { http } = defaultSettings;

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

// const http = '';
// const http = 'http://47.56.198.158:8181'

/**
 *  axioUtil tools
 */
export default class AxiosUtil extends Component {
  static http() {
    return http;
  }

  /**
   * json 转 FormData
   * @param params
   * @returns {FormData}
   */
  static json2FormData(params) {
    const formData = new FormData();
    Object.keys(params).forEach(key => {
      formData.append(key, params[key]);
    });
    return formData;
  }

  static getErrMsg(err) {
    // eslint-disable-next-line no-nested-ternary,max-len
    return err.response !== undefined && err.response.data !== undefined && err.response.data.msg !== undefined
      ? err.response.data.msg
      : codeMessage[err.response.status] !== undefined
        ? codeMessage[err.response.status]
        : '系统错误，请稍后重试！';
  }

  /**
   *  get同步请求
   */
  static getAsync(url, json) {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: http + url,
        data: json,
        dataType: 'json',
        cache: false,
        async: false,
        headers: { Authorization: localStorage.getItem('Authorization') },
        type: 'GET',
        success(res) {
          // 验证是否登录超时
          if (res.code === '998' || res.code === '401') {
            // 登录成功后做对应的逻辑处理
            window.location.href = '/login';
            return;
          }
          if (res.code !== '000') {
            // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
            errorNotification(res.msg !== undefined ? res.msg : '系统异常！');
            reject(res);
            return;
          }
          resolve(res);
        },
        error(err) {
          if (url !== '/web/login/verify') {
            // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
            errorNotification(
              err.response.data !== undefined && err.response.data.msg !== undefined
                ? err.response.data.msg
                : codeMessage[err.response.status] !== undefined
                ? codeMessage[err.response.status]
                : '系统错误，请稍后重试！',
            );
          }
          reject(err);
        },
      });
    });
  }

  /**
   *  get请求
   */
  static get(url, json) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        headers: { Authorization: localStorage.getItem('Authorization') },
        url: http + url,
        params: json === undefined ? {} : json,
      })
        .then(res => {
          // 验证是否登录超时
          if (res.data.code === '998' || res.data.code === '401') {
            // 登录成功后做对应的逻辑处理
            window.location.href = '/login';
            return;
          }
          if (res.data.code !== '000') {
            // eslint-disable-next-line max-len
            // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
            errorNotification(res.data.msg !== undefined ? res.data.msg : '系统异常！');
            reject(res);
            return;
          }
          resolve(res.data);
        })
        .catch(err => {
          if (url !== '/web/login/verify') {
            // eslint-disable-next-line max-len
            // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define,no-nested-ternary
            errorNotification(
              err.response.data !== undefined && err.response.data.msg !== undefined
                ? err.response.data.msg
                : codeMessage[err.response.status] !== undefined
                ? codeMessage[err.response.status]
                : '系统错误，请稍后重试！',
            );
          }
          reject(err);
        });
    });
  }

  /**
   *  post 请求
   */
  static post(url, json) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        headers: { Authorization: localStorage.getItem('Authorization') },
        url: http + url,
        data: json === undefined ? {} : json,
      })
        .then(res => {
          // 验证是否登录超时
          if (res.data.code === '998' || res.data.code === '401') {
            // 登录成功后做对应的逻辑处理
            window.location.href = '/login';
            return;
          }
          if (res.data.code !== '000') {
            // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
            errorNotification(res.data.msg !== undefined ? res.data.msg : '系统异常！');
            reject(res);
            return;
          }
          resolve(res.data);
        })
        .catch(err => {
          // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
          errorNotification(
            err.response.data !== undefined && err.response.data.msg !== undefined
              ? err.response.data.msg
              : codeMessage[err.response.status] !== undefined
              ? codeMessage[err.response.status]
              : '系统错误，请稍后重试！',
          );
          reject(err);
        });
    });
  }

  /**
   *  put 请求
   */
  static put(url, json) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'put',
        headers: { Authorization: localStorage.getItem('Authorization') },
        url: http + url,
        data: json === undefined ? {} : json,
      })
        .then(res => {
          // 验证是否登录超时
          if (res.data.code === '998' || res.data.code === '401') {
            // 登录成功后做对应的逻辑处理
            window.location.href = '/login';
            return;
          }
          if (res.data.code !== '000') {
            // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
            errorNotification(res.data.msg !== undefined ? res.data.msg : '系统异常！');
            reject(res);
            return;
          }
          resolve(res.data);
        })
        .catch(err => {
          // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
          errorNotification(
            err.response.data !== undefined && err.response.data.msg !== undefined
              ? err.response.data.msg
              : codeMessage[err.response.status] !== undefined
              ? codeMessage[err.response.status]
              : '系统错误，请稍后重试！',
          );
          reject(err);
        });
    });
  }

  /**
   * delete 请求
   */
  static delete(url, json) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'delete',
        headers: { Authorization: localStorage.getItem('Authorization') },
        url: http + url,
        data: json === undefined ? {} : json,
      })
        .then(res => {
          // 验证是否登录超时
          if (res.data.code === '998' || res.data.code === '401') {
            // 登录成功后做对应的逻辑处理
            window.location.href = '/login';
            return;
          }
          if (res.data.code !== '000') {
            // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
            errorNotification(res.data.msg !== undefined ? res.data.msg : '系统异常！');
            reject(res);
            return;
          }
          resolve(res.data);
        })
        .catch(err => {
          // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
          errorNotification(
            err.response.data !== undefined && err.response.data.msg !== undefined
              ? err.response.data.msg
              : codeMessage[err.response.status] !== undefined
              ? codeMessage[err.response.status]
              : '系统错误，请稍后重试！',
          );
          reject(err);
        });
    });
  }
}

// eslint-disable-next-line no-shadow
const errorNotification = message => {
  notification.error({
    message: '请求失败',
    description: message,
  });
};
